package com.cddx.logistics.service.impl;

import com.cddx.logistics.domain.dto.SysAnnouncementQueryDTO;
import com.cddx.logistics.domain.pojo.SysAnnouncement;
import com.cddx.logistics.domain.vo.SysAnnouncementVO;
import com.cddx.logistics.mapper.SysAnnouncementMapper;
import com.cddx.logistics.mapper.SysAnnouncementSendMapper;
import com.cddx.logistics.service.SysAnnouncementService;
import com.cddx.logistics.util.model.Result;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class SysAnnouncementServiceImpl implements SysAnnouncementService {
    @Resource
    private SysAnnouncementMapper sysAnnouncementMapper;

    @Resource
    private SysAnnouncementSendMapper sysAnnouncementSendMapper;
    @Override
    public PageInfo<SysAnnouncementVO> queryPage(SysAnnouncementQueryDTO sysAnnouncementQueryDTO) {
        PageHelper.startPage(sysAnnouncementQueryDTO.getPage(),sysAnnouncementQueryDTO.getLimit());
        List<SysAnnouncementVO> sysdictVOList = sysAnnouncementMapper.queryPage(sysAnnouncementQueryDTO);
        PageInfo<SysAnnouncementVO> pageInfo = new PageInfo<>(sysdictVOList);
        return pageInfo;
    }

    @Override
    public void markAllAsRead() {
        sysAnnouncementSendMapper.updateAllReadFlagToRead();
    }

    @Override
    public Result delete(Integer id) {
        return sysAnnouncementMapper.delete(id) > 0 ? Result.ok("删除成功") : Result.error("删除失败");
    }

    @Override
    public void deleteAll(List<Integer> ids) {
        sysAnnouncementMapper.deleteAll(ids);
    }

    @Override
    public boolean addannounce(SysAnnouncement announcement , Object o) {
        int result = sysAnnouncementMapper.insert(announcement);
        if (result > 0 && announcement.getId() != null) {
            // 获取所有用户 ID
            List<Integer> userIds = sysAnnouncementSendMapper.getAllUserIds();

            // 插入所有用户的未读状态
            Integer anntId = announcement.getId();
            for (Integer userId : userIds) {
                sysAnnouncementSendMapper.insert(userId, anntId, 0); // 0=未读
            }

            return true;
        }
        return false;

    }

    @Override
    public boolean insertSendRecord(Integer userId, Integer anntId, Integer readFlag) {
        return sysAnnouncementSendMapper.insert(userId, anntId, readFlag) > 0;
    }

    @Override
    public List<Integer> getAllUserIds() {
        return sysAnnouncementSendMapper.getAllUserIds();
    }



}
